package dao

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Rule struct {
	Ruid int `json:"ru_id" gorm:"column:ru_id"`
	Name string `json:"name" gorm:"column:name"`
	Desc string `json:"desc" gorm:"column:desc"`
	Path string `json:"path" gorm:"column:path"`
	Icon string `json:"icon" gorm:"column:icon"`
	Ctime int64 `json:"c_time" gorm:"column:c_time"`
	Dtime int64 `json:"d_time" gorm:"column:d_time"`
}
func (r *Rule) Create(s map[string]interface{}) (bool,int) {

	var addr Rule
	if v,ok := s["name"];ok{
		addr.Name = v.(string)
	}
	if v,ok := s["desc"];ok{
		addr.Desc = v.(string)
	}
	if v,ok := s["path"];ok{
		addr.Path = v.(string)
	}
	if v,ok := s["icon"];ok{
		addr.Icon = v.(string)
	}
	addr.Ctime = time.Now().Unix()

	err := db.Create(&addr).Error
	b := true
	if err != nil{
		panic(err)
	}
	var id []int
	db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return b,id[0]

}
/**
	软删除
 */
func (r *Rule) Delete(w map[string]interface{}) bool {

	upd := Rule{
		Dtime:time.Now().Unix(),
	}
	err := db.Model(&r).Where(w).Update(upd).Error
	b := true
	if err != nil {
		b = false
	}
	return b

}
/**
	硬删除
 */
func (r *Rule) HardDel(w map[string]interface{}) bool {

	err := db.Where(w).Delete(&r).Error
	b := true
	if err !=nil{
		b = false
	}
	return b

}
/**
	更新
 */
func (r *Rule) Update(w map[string]interface{},f map[string]interface{}) bool {

	fs := &Rule{}
	if v,ok := f["name"];ok{
		fs.Name = v.(string)
	}
	if v,ok := f["icon"];ok{
		fs.Icon = v.(string)
	}
	if v,ok := f["desc"];ok{
		fs.Desc = v.(string)
	}
	if v,ok := f["path"];ok{
		fs.Path = v.(string)
	}

	err := db.Model(&r).Where(w).Updates(fs).Error
	b := true
	if err != nil{
		b = false
	}
	return b

}
/**
	读取结果集
 */
func (r *Rule) Find(w map[string]interface{},page int,pageSize int) ([]*Rule,int, error){

	var total int = 0
	var rs []*Rule
	// 获取取指page，指定pagesize的记录
	err := db.Where(w).Where("d_time = ?","").
		Limit(pageSize).Offset((page-1)*pageSize).
		Order("ru_id desc").Find(&rs).Error

	// 获取总条数
	db.Model(&r).Where(w).Where("d_time = ?","").Count(&total)

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}
	return rs,total,nil

}
/**
	读取单条记录
 */
func (r *Rule) First(w map[string]interface{},f []string) (bool,*Rule){

	err := db.Select(f).Where(w).First(&r).Error

	if err !=nil{
		return false,nil
	}
	return true,r

}
var RuleDao = &Rule{}
